package com.cy.demo.service.impl;

import com.cy.demo.mapper.UserMapper;
import com.cy.demo.pojo.User;
import com.cy.demo.service.IUserService;
import com.cy.demo.service.ex.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.UUID;

//@Service注解：SpringBoot默认整合了SpringMVC框架，所以SpringMVC所有的注解可以直接在SpringBoot下直接使用

@Service//将当前对象交给Spring容器管理,自动创建对象以及对象的维护
public class UserServiceImpl implements IUserService {

    //service层依赖于mapper层，所以我们要创建mapper层的对象
    @Autowired
    private UserMapper userMapper;

    @Override
    public User findByUsername(String username) {
        return userMapper.findByUsername(username);
    }

    @Override
    public void reg(User user) {
        String username = user.getUsername();
        String pwd= user.getPassword();
        //检测用户名是否存在(findByUsername)
        User result = userMapper.findByUsername(username);
        if (result != null) {
            //抛出异常
            throw new UsernameDulicateException("用户名被占用！");
        }else if(username==""|pwd==""){
            throw new InformationUmptyException("用户名或者密码为空");
        }else {
            //密码的加密处理：md5算法的形式：67khjkh-jkhuiyh121-shdjdh37-jhj-67123
            //（串+password+串)----md5算法进行加密，连续加密三次
            //这个串叫盐值，盐值本身就是一个随机的串
            String oldPassword = user.getPassword();
            //获取盐值(随机生成一个盐值)
            String salt = UUID.randomUUID().toString().toUpperCase();
            //不全数据：盐值的记录，因为登录时不比较密码，而是比较加密三次的输入结果与密码
            user.setSalt(salt);
            //将密码和盐值作为一个整体进行加密处理，忽略原有密码强度提升了数据的安全性
            String md5Password=getMD5Pawword(oldPassword,salt);
            //将加密之后的密码重写补全设置到user对象中
            user.setPassword(md5Password);
            //补全数据：is_delete设置为0
            user.setIsDelete(0);
            //补全数据：4个日志信息：
            user.setCreatedUser(user.getUsername());
            user.setModifiedUser(user.getUsername());
            Date date = new Date();
            user.setModifiedTime(date);
            user.setCreatedTime(date);


            Integer rows = userMapper.insert(user);
            if (rows != 1) {
                throw new InsertException("在用户注册过程中产生了未知的异常！");
            }
        }
    }

    @Override
    public User login(String username,String passwrod) {


        User result = userMapper.findByUsername(username);

        if(result==null||result.getIsDelete()==1){
            throw new UsernameNotexistException("用户名不存在！");
        }else {
            String password01 =null;
            password01=getMD5Pawword(passwrod,result.getSalt());
            if(!result.getPassword().equals(password01)){
                throw new PasswordError("密码错误");
            }
        }
        User data = new User();
        data.setUid(result.getUid());
        data.setUsername(result.getUsername());
        data.setAvatar(result.getAvatar());
        return data;

    }

    @Override
    public void updatePassword(String username,String oldPassword,String newPassword) {
        User result = userMapper.findByUsername(username);
        String password=getMD5Pawword(oldPassword,result.getSalt());
        if(result==null||result.getIsDelete()==1){
                throw new UsernameNotexistException("用户名不存在！");

            }else if(!result.getPassword().equals(password)){
                throw new PasswordError("密码错误！");
            }
            String modifiedUser = result.getUsername();
            Date modifiedTime = new Date();
            String newPassword01 = getMD5Pawword(newPassword,result.getSalt());
        Integer rows=userMapper.updatePassword(newPassword01,username,modifiedTime,modifiedUser);
        if (rows != 1) {
            throw new InsertException("在用户注册过程中产生了未知的异常！");
        }
    }

    @Override
    public User getByUid(Integer uid) {
        User user = userMapper.findByUid(uid);
        return user;
    }

    @Override
    public void updateInfo(Integer id, String phone, String email,Integer gender) {
        User result = userMapper.findByUid(id);
        Date modifiedTime = new Date();
        String modifiedUser = result.getUsername();
        if(phone.equals("")){
            throw new PhoneEmpty();
        }else if(email.equals("")){
            throw new EmailEmpty();
        }

        Integer rows= userMapper.updateInfo(id,phone,email,modifiedTime,modifiedUser,gender);

        if(rows!=1){
            throw new InsertException("在用户信息修改的过程中产生了未知的异常！");
        }
    }


    @Override
    public void updateAvatarByUid(Integer uid, String avatar, String modifiedUser) {
        User result = userMapper.findByUid(uid);
        if(result==null||result.getIsDelete()==1){
            throw new UsernameNotexistException("用户不存在！");
        }else{
            Date modifiedDate = new Date();
            Integer rows =userMapper.updateAvatarByUid(uid,avatar,modifiedDate,modifiedUser);
            if(rows!=1){
                throw new InsertException("在上传图片的过程中产生了未知的异常！");
            }
        }


    }

    /**
     * 定义一个md5算法的加密处理
     */
    private String getMD5Pawword(String password, String salt) {

        //MD5加密算法的调用（三次加密）
        for (int i = 0; i < 3; i++) {

            password=DigestUtils.md5DigestAsHex((salt + password + salt).getBytes()).toUpperCase();
        }

        return password;
    }



}
